import lodash from 'lodash';
import { request } from 'umi';
import type { RequestConfig } from 'umi';
import { httpConfig } from '../../setting';

import Token from '../../lib/storage/token';
// import { getLocal } from '../storage/storage';
// import { httpConfig } from '@/setting';

const authHeaderInterceptor = (url: string, options: RequestConfig) => {
  const authHeader = { 'tenant-Id': httpConfig.tenantId };
  return {
    url: `${url}`,
    options: { ...options, interceptors: true, headers: { ...options.headers, ...authHeader } },
  };
};

export { authHeaderInterceptor };

const demoResponseInterceptors = (response: Response, options: RequestConfig) => {
  if (options) {
  }
  return response;
};

export { demoResponseInterceptors };

export class TRequest {
  private options: HTTP.createHttpOption;
  constructor(options: HTTP.createHttpOption) {
    this.options = options;
  }
  request<T = any>(opts: HTTP.opts, data: any, options?: Record<string, any>): Promise<T> {
    return new Promise(async (resolve, reject) => {
      const auth =
        lodash.isBoolean(opts.token) && opts.token === false ? false : this.options.token;

      const result: HTTP.requestResult = await request(this.options.baseUrl + opts.url, {
        method: opts.methods,
        headers: {
          'Content-Type': 'application/json',
          Authorization: auth ? 'Bearer ' + (Token.get().accessToken || '') : '',
        },
        data,
        ...(options || {}),
      });
      if (result.code === 0) {
        resolve(result.data);
      }
      reject(result);
    });
  }
  get<T = any>(url: string, data?: any, options?: Record<string, any>): Promise<T> {
    return this.request(
      {
        url,
        methods: 'GET',
      },
      data,
      options,
    );
  }
  post<T = any>(url: string, data?: any, options?: Record<string, any>): Promise<T> {
    return this.request(
      {
        url,
        methods: 'POST',
      },
      data,
      options,
    );
  }
  put<T = any>(url: string, data?: any, options?: Record<string, any>): Promise<T> {
    return this.request(
      {
        url,
        methods: 'PUT',
      },
      data,
      options,
    );
  }
}
